<?php

namespace App\Ext;

use Redis;

class RedisCache
{
    private $connect;

    function __construct($db = 0)
    {
        $this->connect = $this->connect($db);
    }

    /**
     * 连接Redis数据库
     *
     * @param int $db 库名
     * @return Redis
     */
    public function connect($db = 0) {
        $host = env('REDIS_HOST');
        $port = env('REDIS_PORT');
        $redis = new Redis;
        $redis->connect($host, $port);
        return $redis;
    }

    /**
     * 检查缓存是否存在
     *
     * @param $key
     * @return bool
     */
    public function check($key)
    {
        if ($this->connect->exists($key) == 1) return true;
        return false;
    }

    /**
     * 保存Hash数组缓存
     *
     * @param $key
     * @param $param
     * @param null $time
     * @return bool
     */
    public function setHash($key, $param, $time = null)
    {
        if (is_array($param)) {
            if ($this->connect->hMset($key, $param)) {
                if ($time) {
                    $this->connect->expireAt($key, time() + $time);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 修改Hash数组缓存
     *
     * @param $key
     * @param $param
     * @param null $time
     * @return bool
     */
    public function updateHash($key, $param, $time = null)
    {
        if (is_array($param)) {
            foreach ($param as $k => $val) {
                if (!$this->connect->hSet($key, $k, $val)) return false;
            }
            if ($time) {
                $this->connect->expireAt($key, time() + $time);
            }
            return true;
        }
        return false;
    }

    /**
     * 保存字符串缓存
     *
     * @param $key
     * @param $param
     * @param null $time
     * @return bool
     */
    public function set($key, $param, $time = null)
    {
        if ($time) {
            if ($this->connect->setex($key, $time, $param)) return true;
        } else {
            if ($this->connect->set($key, $param)) return true;
        }
        return false;
    }

    /**
     * 读取Hash数组缓存
     *
     * @param $key
     * @param null $param
     * @return array|string
     */
    public function getHash($key, $param = null)
    {
        if ($param) {
            if (is_array($param)) {
                return $this->connect->hMget($key, $param);
            } else {
                return $this->connect->hGet($key, $param);
            }
        } else {
            return $this->connect->hGetAll($key);
        }
    }

    /**
     * 读取字符串缓存
     *
     * @param $key
     * @return bool|string
     */
    public function get($key)
    {
        return $this->connect->get($key);
    }

    /**
     * 删除缓存
     *
     * @param $key
     */
    public function del($key)
    {
        return $this->connect->delete($key);
    }

}